package com.bowlong.net.http;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import com.bowlong.io.ByteOutStream;
import com.bowlong.objpool.ByteOutPool;

public class HttpEx {
	public static final byte[] readUrl(String url) throws Exception {
		try (InputStream is = openUrl(url);) {
			return readStream(is);
		}
	}

	public static final byte[] readUrl(String url, byte[] post)
			throws Exception {
		HttpURLConnection huc = openUrl(url, post);
		try (InputStream is = huc.getInputStream();) {
			return readStream(is);
		} finally {
			huc.disconnect();
		}
	}

	public static final byte[] readUrl(URL url) throws Exception {
		try (InputStream is = openUrl(url);) {
			return readStream(is);
		}
	}

	public static final InputStream openUrl(String url) throws Exception {
		return openUrl(new URL(url));
	}

	// public static final InputStream openUrl(String url, byte[] post)
	// throws Exception {
	// URL u = new URL(url);
	// HttpURLConnection huc = (HttpURLConnection) u.openConnection();
	// huc.setDoOutput(true);
	// huc.setRequestMethod("POST");
	// huc.setRequestProperty("Content-type", "text/html; charset=utf-8");
	// huc.setRequestProperty("Connection", "close");
	// huc.setRequestProperty("Content-Length", post.length + "");
	// huc.getOutputStream().write(post);
	// huc.getOutputStream().flush();
	// huc.getOutputStream().close();
	// return huc.getInputStream();
	// }

	public static HttpURLConnection openUrl(String url, byte[] post)
			throws Exception {
		URL u = new URL(url);
		HttpURLConnection huc = (HttpURLConnection) u.openConnection();
		huc.setDoOutput(true);
		huc.setRequestMethod("POST");
		huc.setRequestProperty("Content-type", "text/html; charset=utf-8");
		huc.setRequestProperty("Connection", "close");
		huc.setRequestProperty("Content-Length", String.valueOf(post.length));
		huc.getOutputStream().write(post);
		huc.getOutputStream().flush();
		huc.getOutputStream().close();
		return huc;
	}

	public static final InputStream openUrl(URL url) throws IOException {
		return url.openStream();
	}

	private static byte[] readStream(InputStream is) throws IOException {
		byte[] buf = new byte[1024];
		try (ByteOutStream out = ByteOutPool.borrowObject();) {
			int times = 1000;
			while (true) {
				if (times-- <= 0)
					break;
				int len = is.read(buf);
				if (len <= 0)
					break;
				out.write(buf, 0, len);
			}
			return out.toByteArray();
		}
	}

	// private static final ByteOutStream newStream(int size) {
	// return new ByteOutStream(size);
	// }

}
